package cn.zmwh.manage.admin.modules.upms.service;

import cn.zmwh.common.core.exception.RRException;
import cn.zmwh.common.security.base.BaseUserDetails;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import cn.zmwh.manage.admin.modules.upms.mapper.SysUserMapper;
import cn.zmwh.manage.admin.modules.upms.pojo.entity.SysUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-03-11
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> implements UserService, UserDetailsService {


    private UserDetails userToUserDetails(SysUser user) {
        Integer enabled = user.getEnabled() == null ? 1 : user.getEnabled();
        if (enabled == 2) {
            throw new RRException("账号被禁用！");
        }
        Long id = user.getId();
        String username = user.getMobile();
        String nick = user.getNickname();
        BaseUserDetails userDetail = new BaseUserDetails(id, id, nick, username, "", new HashSet<>());
        return userDetail;
    }


    @Override
    public UserDetails loadUser(LoginDTO request) {
        SysUser user = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getMobile, request.getMobile()));
        if (user == null) {
            throw new RRException("用户不存在");
        }
        return userToUserDetails(user);
    }

    @Override
    public UserDetails loadUserById(Long id) {
        SysUser sysUser = baseMapper.selectById(id);
        if (sysUser == null) {
            throw new RRException("用户不存在");
        }
        return userToUserDetails(sysUser);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = baseMapper.selectOne(Wrappers.<SysUser>lambdaQuery()
                .eq(SysUser::getMobile, username));
        if (user == null) {
            throw new RRException("用户不存在");
        }
        return userToUserDetails(user);
    }

}
